package com.snsoft.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.snsoft.bean.Base;
import com.snsoft.bean.BaseInfo;
import com.snsoft.bean.GreenHouse;
import com.snsoft.bean.GreenHouseInfo;
import com.snsoft.bean.Sensor;
import com.snsoft.bean.SensorInfo;
import com.snsoft.bean.UserInfo;
import com.snsoft.exception.BaseNotFound;
import com.snsoft.exception.GreenHouseNotFound;
import com.snsoft.exception.SensorNotFound;
import com.snsoft.service.environment.GetBaseInfoService;
import com.snsoft.service.environment.GetBaseListService;
import com.snsoft.service.environment.GetForecastService;
import com.snsoft.service.environment.GetGreenHouseInfoService;
import com.snsoft.service.environment.GetGreenHouseListService;
import com.snsoft.service.environment.GetHistoryDataService;
import com.snsoft.service.environment.GetNewDataService;
import com.snsoft.util.Constants;
import com.snsoft.util.JsonUtils;

/**
 * 
 * @copyright ：神农大学生软件创新中心 版权所有 © 2017
 * 
 * @author 16计算机弓耀
 * 
 * @version 1.0
 * 
 * @date 2017年11月5日下午10:06:10
 * 
 * @Description TODO 环境监测模块控制器
 */
@WebServlet("/environment")
public class EnvironmentController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public EnvironmentController() {
		super();
	}

	/**
	 * 接口分流
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		if (method != null && method.trim().length() > 0) {
			if ("getBaseList".equals(method)) {
				this.getBaseList(request, response);
			} else if ("getBaseInfo".equals(method)) {
				this.getBaseInfo(request, response);
			} else if ("getGreenHouseList".equals(method)) {
				this.getGreenHouseList(request, response);
			} else if ("getGreenHouseInfo".equals(method)) {
				this.getGreenHouseInfo(request, response);
			} else if ("getNewData".equals(method)) {
				this.getNewData(request, response);
			} else if ("getHistoryData".equals(method)) {
				this.getHistoryData(request, response);
			} else if ("getForecast".equals(method)) {
				this.getForecast(request, response);
				
			}
		} else {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "请求异常！"));
		}
	}

	/**
	 * 接口分流
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "请求异常！"));
	}

	/**
	 * 获取基地列表接口
	 */
	private void getBaseList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 校验用户登陆
		if (request.getSession(false).getAttribute("userInfo") == null) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "用户未登陆"));
		} else {
			UserInfo user = (UserInfo) request.getSession(false).getAttribute("userInfo");
			if (user.getRole() != 1 && user.getRole() != 2) {
				response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "权限不足"));
				return;
			}
			// 获取基地列表
			List<BaseInfo> list = null;
			GetBaseListService gs = new GetBaseListService();
			try {
				if (user.getRole() == 1) {
					list = gs.getBaseListBySuper();
				} else {
					list = gs.getBaseList(user.getUserID() + "");
				}
			} catch (SQLException e) {
				response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, Constants.JSON_ERROR));
				return;
			} catch (BaseNotFound e) {
				response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "该用户没有基地！"));
				return;
			}
			response.getWriter().write(JsonUtils.objectToJson(list, Constants.CODE_SUCCESS, "获取成功！"));
		}
	}

	/**
	 * 获取基地信息接口
	 */
	private void getBaseInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 校验用户登陆
		UserInfo user = (UserInfo) request.getSession(false).getAttribute("userInfo");
		if (user.getRole() != 1 && user.getRole() != 2) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "权限不足"));
			return;
		}
		// 校验参数
		if (StringUtils.isEmpty(request.getParameter("companyID"))) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "基地ID不能为空"));
			return;
		}
		Base base = null;
		GetBaseInfoService gs = new GetBaseInfoService();

		try {
			base = gs.getBaseInfo(Integer.parseInt(request.getParameter("companyID").toString()));
		} catch (NumberFormatException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "输入参数类型错误"));
			return;
		} catch (SQLException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, Constants.JSON_ERROR));
			return;
		} catch (BaseNotFound e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "基地不存在"));
			return;
		}
		response.getWriter().write(JsonUtils.objectToJson(base, Constants.CODE_SUCCESS, "获取成功！"));
	}

	/**
	 * 获取温室列表接口
	 */
	private void getGreenHouseList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 校验参数
		if (StringUtils.isEmpty(request.getParameter("companyID"))) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "基地ID不能为空"));
			return;
		}
		if(request.getSession().getAttribute("userInfo") == null) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "请先登录"));
			return;
		}
		UserInfo user = (UserInfo) request.getSession().getAttribute("userInfo");
		List<GreenHouseInfo> list = null;
		GetGreenHouseListService gs = new GetGreenHouseListService();
		try {
			if(user.getRole() == 0) {
				list = gs.getGreenHouseListByCommon(user.getUserID() + "");
			}else if(user.getRole() == 1 || user.getRole() == 2) {
				list = gs.getGreenHouseList(Integer.parseInt(request.getParameter("companyID").toString()));
			}
		} catch (BaseNotFound e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "基地不存在"));
			return;
		} catch (NumberFormatException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "输入参数类型错误"));
			return;
		} catch (SQLException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, Constants.JSON_ERROR));
			return;
		} catch (GreenHouseNotFound e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "温室不存在"));
			return;
		}
		response.getWriter().write(JsonUtils.objectToJson(list, Constants.CODE_SUCCESS, "获取成功！"));
	}

	/**
	 * 获取温室信息接口
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void getGreenHouseInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 校验参数
		if (StringUtils.isEmpty(request.getParameter("greenHouseID"))) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "温室 ID不能为空"));
			return;
		}
		GreenHouse green = null;
		GetGreenHouseInfoService gs = new GetGreenHouseInfoService();
		try {
			green = gs.getGreenHouseInfo(Integer.parseInt(request.getParameter("greenHouseID").toString()));
		} catch (NumberFormatException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "输入参数类型错误"));
			return;
		} catch (SQLException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, Constants.JSON_ERROR));
			return;
		} catch (GreenHouseNotFound e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "温室不存在"));
			return;
		}
		response.getWriter().write(JsonUtils.objectToJson(green, Constants.CODE_SUCCESS, "获取成功！"));
	}

	/**
	 * 获取温室中传感器最新数据接口
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void getNewData(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 校验参数
		if (StringUtils.isEmpty(request.getParameter("greenHouseID"))) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "温室 ID不能为空"));
			return;
		}
		if (StringUtils.isEmpty(request.getParameter("time"))) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "数据时间范围不能为空"));
			return;
		}
		List<Sensor> list = null;
		GetNewDataService gs = new GetNewDataService();
		try {
			list = gs.getNewData(Integer.parseInt(request.getParameter("greenHouseID").toString()),
					Integer.parseInt(request.getParameter("time").toString()));
		} catch (NumberFormatException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "输入参数类型错误"));
			return;
		} catch (SQLException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, Constants.JSON_ERROR));
			return;
		} catch (SensorNotFound e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "传感器数据不存在"));
			return;
		}
		response.getWriter().write(JsonUtils.objectToJson(list, Constants.CODE_SUCCESS, "获取成功！"));
	}

	/**
	 * 获取单个传感器历史数据接口
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void getHistoryData(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 校验参数
		if (StringUtils.isEmpty(request.getParameter("protocolID"))) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "协议 ID不能为空"));
			return;
		}
		if (StringUtils.isEmpty(request.getParameter("deviceID"))) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "设备 ID不能为空"));
			return;
		}
		if (StringUtils.isEmpty(request.getParameter("nodeID"))) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "节点 ID不能为空"));
			return;
		}
		if (StringUtils.isEmpty(request.getParameter("time"))) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "数据时间范围不能为空"));
			return;
		}
		GetHistoryDataService gs = new GetHistoryDataService();
		List<SensorInfo> list = null;
		try {
			list = gs.getHistoryData(Integer.parseInt(request.getParameter("protocolID").toString()),
					Integer.parseInt(request.getParameter("deviceID").toString()),
					Integer.parseInt(request.getParameter("nodeID").toString()),
					Integer.parseInt(request.getParameter("time").toString()));
		} catch (NumberFormatException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "输入参数类型错误"));
			return;
		} catch (SQLException e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, Constants.JSON_ERROR));
			return;
		} catch (SensorNotFound e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "传感器数据不存在"));
			return;
		}
		response.getWriter().write(JsonUtils.objectToJson(list, Constants.CODE_SUCCESS, "获取成功！"));
	}

	/**
	 * 获取天气预报信息接口测试
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws InterruptedException 
	 */
	private void getForecast(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 校验用户登陆
		if (request.getSession(false).getAttribute("userInfo") == null) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "用户未登陆"));
		} else {
			UserInfo user = (UserInfo) request.getSession(false).getAttribute("userInfo");
			List<Base> list = null;
			HashMap<String, Object> res = new HashMap<String,Object>();
			GetForecastService gs = new GetForecastService();
			try {
				list = gs.getBaseList(user.getUserID() + "");
				for(Base base : list) {
					res.put("location", base.getLocation());
					String weather = gs.getForecast(base.getLocation());
					res.put("weather", weather);
					Date date=new Date();
					DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String time = format.format(date);
					res.put("time", time);
					
				}
			} catch (SQLException e) {
				response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, Constants.JSON_ERROR));
				return;
			} catch (BaseNotFound e) {
				response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "基地不存在"));
				return;
			}
			response.getWriter().write(JsonUtils.objectToJson(res, Constants.CODE_SUCCESS, "获取成功！"));
			
		}

	}
}
